﻿//全局变量
var table, myGrid, ised = "";

$(document).ready(function () {


    GetMenuButtonList('btnOp');
    //#region datatable初始化及值绑定
    $.extend($.fn.dataTable.defaults, {
        dom: 'rt<"#dt-bottom.row"<"col-xs-2"l><"col-xs-7"p><"col-xs-3"i>>'
    });
    var scrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
    //适应窗口大小变化
    $(window).resize(function () {
        var newScrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
        $('.dataTables_scrollBody').css('height', newScrollY);
    });
    myGrid = {
        id: 'dt_admin',
        isenable: false,//是否需要禁用启用按钮
        scrollY: scrollY,
        paging: true,
        hasIndex: true,
        multiSelect: true,
        processing: true,
        serverSide: true,
        columns: [
                { data: "Row", title: "#" },
                { data: "cardno", title: "卡号" },
                { data: "cardTypes", title: "卡类型" },
                { data: "activationstate", title: "状态" },
                { data: "isusestatus", title: "是否已发放实体卡" },
                { data: "createtime", title: "创建时间" },
                { data: "starttime", title: "有效期起" },
                { data: "endtime", title: "有效期止" },
                { data: 'name', title: '激活人员' },
                { data: 'mobile', title: '联系电话' },
                { data: 'remark', title: '备注' },
                { data: 'activationstate', title: '操作' },
        ],
        columnDefs: [
            {
                render: function (data, type, row) {
                    if (data == 0) {
                        return "未激活";
                    }
                    if (data == 1) {
                        return "已激活";
                    } else {
                        return "已弃用";
                    }
                },
                targets: [3]
            },
            {
                render: function (data, type, row) {
                    if (data == 1) {
                        return "是";
                    }else {
                        return "否";
                    }
                },
                targets: [4]
            },
            {
                render: function (data, type, row) {
                    if (data == 1) {
                        return "<a href=ActivationManage?id=" + row.cardno + "&actions=readonly>查看</a>";
                    } else {
                        return "";
                    }
                },
                targets: [11]
            }],
        order: [[1, 'asc']],
        data: {},
        ajax: function (data, callback, settings) {
            //封装请求参数
            var reUrl = 'GetCards';
            var order = data.columns[data.order[0].column].data + " " + data.order[0].dir;
            var pagesize = data.length;
            var pageno = (data.start / data.length) + 1;
            //查询条件
            var searchData = { pagesize: pagesize, pageno: pageno, order: order, query: $('#query').val(), startTime: $('#date_st').val(), endTime: $('#date_ed').val(), carstate: $('#carstate').val() };
            //ajax请求数据
            $.ajax({
                type: "GET",
                url: reUrl,
                cache: false,//禁用缓存
                data: searchData,//传入组装的参数
                dataType: "json",
                //headers: param,//请求头参数
                success: function (result, status, xhr) {
                    //封装返回数据
                    var returnData = {};
                    returnData.draw = data.draw; //这里直接自行返回了draw计数器,应该由后台返回
                    returnData.recordsTotal = result.TotalCount;
                    total_curr = result.TotalCurr;
                    returnData.recordsFiltered = result.TotalCount; //后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = result.Entity; //返回的数据列表
                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                    callback(returnData);//将你的返回的data转为datatables能识别的数据格式作为参数返回ajax的callback回调中。
                }
            });
        }
    }
    table = DataBind(myGrid);
    //#endregion 
    $('#btnCardSave').click(function () {
        AjaxSave();
    });
    $('#btnCardUpdate').click(function () {
        AjaxSaveCard();
    });

    $('#datetimepicker_st,#datetimepicker_ed,#datetimepicker_start1,#datetimepicker_end1,#datetimepicker_start,#datetimepicker_end').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $('#btnInquire').click(function () {
        loadTableData();
    })

});

function GetCard() {
    var obj = {};
    obj.id = $('#id').val();
    obj.cardtype = $('#cardtype1').val();
    obj.cardno = $('#cardno').val();
    obj.starttime = $('#starttime1').val();
    obj.endtime = $('#endtime1').val();
    obj.activationstate = $('#activationstate').val();
    obj.origin = $('#origin').val();
    return obj;
}

function AjaxSaveCard() {
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveOneCard?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetCard()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#UpdateModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });

}


var Btn_AddTmp = function () {
    $("#cardtype").val('');
    $("#starttime").val('');
    $("#endtime").val('');
    $("#startcard").val('0');
    $("#endcard").val('1000');
    $("#origin1").val('');
    $('#InsuranceAccountAddModal').modal('show');
}

//新增
var Btn_Add = function () {
    $('#title').text("新增救援卡");
    $('#id').val('-1');
    $("#cardtype1").val('');
    $("#cardno").val('');
    $("#starttime1").val('');
    $("#endtime1").val('');
    $("#origin").val('');
    $("#activationstate").val('');
    $('#UpdateModal').modal('show');
}

//编辑
var Btn_Edit = function () {
    if (table.rows('.selected').data().length == 0 || table.rows('.selected').data().length>1) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选中一条数据进行编辑！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    var seletedItem = table.rows('.selected').data()[0];
    $('#title').text("更新救援卡");
    $('#id').val(seletedItem.id);
    $("#cardtype1").val(seletedItem.cardtype);
    $("#cardno").val(seletedItem.cardno);
    $("#starttime1").val(seletedItem.starttime);
    $("#endtime1").val(seletedItem.endtime);
    $("#activationstate").val(seletedItem.activationstate);
    $("#origin").val(seletedItem.origin);

    $('#UpdateModal').modal('show');
}

//刷新datatable
function loadTableData() {
    table.ajax.reload();
}

function GetValues() {
    var obj = {};
    obj.cardtype = $("#cardtype").val();
    obj.starttime = $("#starttime").val();
    obj.endtime = $("#endtime").val();
    obj.startcard = $("#startcard").val();
    obj.endcard = $("#endcard").val();
    obj.origin = $("#origin1").val();
    return obj;
}

function AjaxSave() {
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveCard?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#InsuranceAccountAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}

var Btn_Recovery = function() {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要回收的卡！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
    }
    bconfirm("确定回收发放？", RecoveryCard);
};

function RecoveryCard() {
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].id);
    }
    $.ajax({
        type:"POST",
        url: "RecoveryCard?t=" + new Date().getTime(),
        data: {ids : ids.join()},
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}

//删除
var Btn_Delete = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要删除的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    bconfirm("确定删除？", LogDelete);
}
//删除方法
function LogDelete() {
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].id);
    }
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "DeleteCard?ids=" + ids.join() + "&t=" + new Date().getTime(),
        data: "",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
var Btn_Send = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择已发放的卡进行更新！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].id);
    }
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "UpdateIsusestatus?ids=" + ids.join() + "&t=" + new Date().getTime(),
        data: "",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });

};